//
//  MYListViewModel.swift
//  NewMicroblog
//
//  Created by apple on 2016/10/26.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import SDWebImage

class MYListViewModel: NSObject {
    
    //保存数据数组
    var dataArr: [MYStatusViewModel] = [MYStatusViewModel]()
    
    /// 加载网络数据
    ///
    /// - parameter callBack: 将加载玩的数据返回
    func getHomeData(isPullUP:Bool, callBack:@escaping (Bool,String) -> ()){
        var sinceId:Int64 = 0
        var maxId: Int64 = 0
        if isPullUP {
            maxId = dataArr.last?.listModel?.id ?? 0
            if maxId > 0 {
                maxId -= 1
            }
            sinceId = 0
        }else{
            sinceId = dataArr.first?.listModel?.id ?? 0
            maxId = 0
        }

        let message = "没有加载到最新微博数据"
        MYNetworkingTool.shareTool.homeLoadData(sinceId: sinceId, maxId: maxId, success: { (respons) in
            
            guard let listDict = respons as?[String: Any]else{
                callBack(false,message)
                return
            }
            guard let arrData = listDict["statuses"] as?[[String: Any]] else{
                callBack(false,message)
                return
            }
            
            let dataArray = NSArray.yy_modelArray(with: MYListModel.self, json: arrData) as! [MYListModel]
//            print(dataArray)
            var tempArr:[MYStatusViewModel] = [MYStatusViewModel]()
            for model in dataArray{
                let statusViewModel = MYStatusViewModel()
                statusViewModel.listModel = model
                tempArr.append(statusViewModel)
                
            }
            if isPullUP{
                self.dataArr = self.dataArr + tempArr
            }else{
                self.dataArr = tempArr + self.dataArr
            }
            self.loadSingeImage(array: tempArr, finish: callBack)
        }) { (error) in
            print(error,"请求失败")
            callBack(false,message)
        }
        
    }

}
extension MYListViewModel{
    
    // 单张图片下载
    func loadSingeImage(array: [MYStatusViewModel], finish:@escaping (Bool,String)->()){
        
        // 创建调度组
        let group = DispatchGroup()
        
        // 遍历数组
        for statusViewModel in array {
            
            // 如果是原创微博 && count == 1
            
            if statusViewModel.listModel?.pic_urls?.count == 1 {
                let url = URL(string: statusViewModel.listModel?.pic_urls?.first?.thumbnail_pic ?? "")!
                group.enter()
                SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (image, error, _, _, _) in
                    print("原创微博图片下载完成")
                    group.leave()
                })
                
            }
            
            // 如果是转发微博 && count == 1
            if statusViewModel.listModel?.retweeted_status?.pic_urls?.count == 1 {
                let url = URL(string:
                    statusViewModel.listModel?.pic_urls?.first?.thumbnail_pic ?? "")
                group.enter()
                SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (image, error, _, _, _) in
                    print("转发微博图片下载完成")
                    group.leave()
                })
            }
        }
        
        // 调度组统一监听单张图片是否全部下载完成
        group.notify(queue: .main) {
            print("所有图片全部下载完成")
            var message = "没有加载到最新微博数据"
            if array.count > 0 {
                message = "加载了\(array.count)条微博数据"
            }

            // 代表成功
            finish(true,message)
        }
    }

    
}

